<?php

namespace App\Logic\Order;

use App\Component\LogListForm;
use App\Core\BaseCore;
use App\Core\BaseForm;
use App\Core\BaseListForm;
use App\Core\BaseModel;
use App\Core\Exception\DefaultException;
use App\Core\Exception\ValidationException;
use App\Core\Output;
use App\Enums\ValidateEnums;
use App\HttpController\Api\Order;
use App\Logic\Account\RechargeService;
use App\Logic\Group\GroupProfitService;
use App\Logic\Member\MemberProfitScoreService;
use App\Logic\Shipping\ShippingService;
use App\Model\Member\MemberModel;
use App\Model\Member\MemberProfitScoreModel;
use App\Model\Member\MemberScoreModel;
use App\Model\Order\OrderModel;
use App\Logic\Order\Form\SubmitOrderForm;
use App\Logic\Order\Form\OrderListForm;
use App\Model\Order\OrderReturnedModel;
use App\Util\ArrayHelper;
use App\Util\CommonHelper;
use App\Util\UserIdentityHelper;
use EasySwoole\Component\Di;
use EasySwoole\Component\Singleton;
use EasySwoole\EasySwoole\Config as ESConfig;
use EasySwoole\Http\Request;
use EasySwoole\Log\Logger;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\Redis\Redis;
use EasySwoole\RedisPool\RedisPool;
use EasySwoole\Utility\Random;
use EasySwoole\Validate\Validate;
use Throwable;
use function PHPUnit\Framework\throwException;

class OrderReturnedService extends BaseCore
{

    use Singleton;

    private $op = '<';//用于测试的时候调试

    /**将上个月的数据归档*/
    public function archiveOrder()
    {
        /**取出本月以前(created_at)的前1000条记录*/
        $last_date = date('Y-m-01');
//        $last_date = date('Y-m-d', strtotime('-30 days'));
        $result = OrderReturnedModel::makeQueryModel()
            ->where('created_at', $last_date . ' 00:00:00', '<')
            ->limit(OrderReturnedModel::ORDERLIMIT * 10)//
            ->order('created_at', 'ASC')
            ->order('id', 'ASC')
            ->all();
        $data = [];
        if ($result){
            foreach ($result as $order) {
                $date = date('Ym', strtotime($order->created_at));
                if(!isset($data[$date])){
                    $data[$date] = [];
                }
                $order_array = $order->toRawArray();
                $order_array['profit_chain'] = $order_array['profit_chain'] ?? '';
                $data[$date][] = $order_array;
            }
            foreach ($data as $date => $orders){
                $table_name = 'ss_order_' . $date;
                $this->createArchiveTable($date);
                try {
                    DbManager::getInstance()->startTransactionWithCount('write');
                    $order_ids = array_column($orders, 'id');
                    OrderReturnedModel::create()->connection('write')->where(['id' => [$order_ids, 'in']])->lockForUpdate()->all();
                    /**归档订单*/
                    BaseModel::create()->insertMulti($orders, BaseModel::INSERT_INTO, [], $table_name);
                    /**删除订单*/
                    OrderReturnedModel::create()->connection('write')->destroy(['id' => [$order_ids, 'in']]);

                    DbManager::getInstance()->commitWithCount('write');
                }catch (\Exception $e){
                    DbManager::getInstance()->rollbackWithCount('write');
                    throw $e;
                }
            }
        }
        return true;
    }

    /**创建订单归档的表*/
    public function createArchiveTable($date): void
    {
        $table_name = 'ss_order_' . $date;
        $originalTable = OrderReturnedModel::create()->connection('write')->getTableName();
        $query = new QueryBuilder();
        $sql = <<<sql
            CREATE TABLE If Not Exists {$table_name} LIKE {$originalTable};
sql;
        $query->raw($sql);
        DbManager::getInstance()->query($query);
    }
    /**按月份分表*/
    public function archiveRecordMonth()
    {
        $table = OrderModel::create()->getTableName();
        $origin_table = $table . '_returned';
        CommonHelper::archiveRecordMonth($table, $origin_table);
        return true;
    }
}
